import React from 'react';
import { BasicLayout, BlankLayout } from '@/layouts';
import { message, notification } from 'antd';
import { history } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { currentUser as queryCurrentUser } from './services/user';
import { BookOutlined, LinkOutlined } from '@ant-design/icons';

const isDev = process.env.NODE_ENV === 'development';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <div>加载中...</div>,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState() {
  const fetchUserInfo = async () => {
    try {
      const currentUser = await queryCurrentUser();
      return {...currentUser.data ,permissions:currentUser.permissions};
    } catch (error) {
      history.push('/user/login');
    }
    return undefined;
  };
  // 如果是登录页面，不执行
  if (history.location.pathname !== '/user/login') {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout = ({ initialState, setInitialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== '/user/login') {
        history.push('/user/login');
      }
    },
    links: [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
        </>
      );
    },
    ...initialState?.settings,
  };
};
/**
 * 异常处理程序
 * @see https://beta-pro.ant.design/docs/request-cn
 */
export const request = {
  errorHandler: (error) => {
    const { response } = error;
    console.log(error);
    console.log(response);
    if (response && response.status) {
      const errorText = response.statusText;
      const { status, url } = response;
      if (status === 401) {
        notification.error({
        message: `登录认证已超时，请重新登录`,
        description: errorText,
      });
        history.push('/user/login');
        return;
      }
      notification.error({
        message: `请求错误 ${status}: ${url}`,
        description: errorText,
      });
    } else if(response && !response.success){
      notification.error({
        message:response.message,
      });
      return;
    }

    if (!response) {
      notification.error({
        description: '您的网络发生异常，无法连接服务器',
        message: '网络异常',
      });
    }
    throw error;
  },
  requestInterceptors: [(url, options) => {
    const token = localStorage.getItem('token');
    const authHeader = { Authorization: 'Bearer '+token };
    return {
      url: `${url}`,
      options: { ...options, interceptors: true, headers: authHeader },
    };
  }],
};